package com.controller;


import com.domain.Announcement;
import com.domain.Book;
import com.entity.PageResult;
import com.service.AnnouncementService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/announcement")
public class AnnouncementController {
    @Autowired
    private AnnouncementService announcementService;

    //显示公告
    @RequestMapping("/searchAnnouncement")
    public ModelAndView searchAnnouncement(){
        ModelAndView modelAndView = new ModelAndView();
        //数据
        int pageNum = 1;
        int pageSize = 10;
        PageResult pageResult = announcementService.searchAnnouncement(pageNum, pageSize);
        modelAndView.addObject("pageResult", pageResult);
        //视图
        modelAndView.setViewName("announcement");
        System.out.println(pageResult.getRows());
        return modelAndView;
    }

    //显示详细的公告内容
    @ResponseBody
    @RequestMapping("/findById")
    public Result<Book> findById(String id) {
        try {
            Announcement announcement = announcementService.findById(id);
            if (announcement == null) {
                return new Result(false, "查询公告失败！");
            }
            return new Result(true, "查询公告成功", announcement);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询公告失败！");
        }
    }

    //增加公告
    @ResponseBody
    @RequestMapping("/addAnnouncement")
    public Result addAnnouncement(Announcement announcement) {
        try {
            Integer count = announcementService.addannouncement(announcement);
            if (count != 1) {
                return new Result(false, "新增公告失败!");
            }
            return new Result(true, "新增公告成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "新增公告失败!");
        }
    }

    //删除公告
    @ResponseBody
    @RequestMapping("/delAnnouncement")
    public Result delUser(String id) {
        try {
            announcementService.delAnnouncement(id);
            return new Result(true, "删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败!");
        }
    }

    //更新公告
    @ResponseBody
    @RequestMapping("/editAnnouncement")
    public Result editAnnouncement(Announcement announcement) {
        try {
            announcementService.editAnnouncement(announcement);
            return new Result(true, "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败!");
        }
    }

}
